package uk.co.douglashoskins.weathercompare.services;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class NetQueue {
	private class NetQueueItem {
		public final String url;
		public final NetQueueCallback callback;
		public NetQueueItem(String url, NetQueueCallback callback) {
			this.url = url;
			this.callback = callback;
		}
	}
	
	private Vector queue = new Vector();
	
	public NetQueue() {
		new Thread(new Runnable() {
			
			public void run() {
				while (true) {
					try {
						if (queue.size() > 0) {
							NetQueueItem item = null;
							synchronized (queue) {
								item = (NetQueueItem) queue.elementAt(0);
								queue.removeElement(item);
							}
							try {
								HttpConnection conn = (HttpConnection) Connector.open(item.url);
								InputStream is = conn.openInputStream();
								ByteArrayOutputStream baos = new ByteArrayOutputStream();
								int i;
								while ((i = is.read()) != -1) {
									baos.write(i);
								}
								is.close();
								baos.close();
								item.callback.netCallback(new String(baos.toByteArray()));
								conn.close();
							} catch (Exception e) {
								item.callback.netException(e);
							}
						}
						
						Thread.sleep(1000);
					} catch (InterruptedException e) {}
				}
			}
		}).start();
	}
	
	public void addRequest(String url, NetQueueCallback callback) {
		queue.addElement(new NetQueueItem(url, callback));
	}
}
